#!/user/bin/python
# -*- coding:utf-8 -*-
#filename:dbhandle/redisdb.py

'''
Redis key value 数据库链接操作管理

链接池创建链接
执行set和get等基本操作


db = 0 key&session db
db = 1 other
 
Created on 2011-8-23

@author: zc


'''

import redis

"""redis 最大连接数"""
MAX_CONNECTIONS = 128


class redisdb():
    '''
    redis 数据库链接操作管理
    '''


    def __init__( self, db ):
        '''设置并redis
            参数db为需要连接的数据库
        '''
        self.__dbhost = "127.0.0.1"
        self.__dbname = db
        self.__port = 6379
        self.__max_connections = MAX_CONNECTIONS
        self.__pool = redis.ConnectionPool( host = self.__dbhost, db = self.__dbname, port = self.__port, max_connections = self.__max_connections )
        self.__r = redis.Redis( connection_pool = self.__pool )
        

    def set( self, key, val ):
        """ 设置传入的key val值到redis """
        return self.__r.set( key, val )
        
    
    def get( self, key ):
        """ 根据传入key返回val """
        return self.__r.get( key )
        
    
    def delete( self, key ):
        """ 删除传入key的记录 """
        return self.__r.delete( key )
    
    
    def expire( self, key, secs ):
        """ 设置key失效时间 单位：秒"""
        return self.__r.expire( key, secs ) 


    def zadd( self, key, val, score, **kwarg ):
		"""增加有序集合 		"""
		return self.__r.zadd( key, val, score, **kwarg )


    def zrevrange( self, key, start, num ):
        """有序集合逆序输出        """
        return self.__r.zrevrange( key, start, num )

    
if __name__ == '__main__':
	r = redisdb()
    #print r.set('ttt','0000')
    #t = r.get('ttt')
	r.zadd( 'hotfeet', 'p1,1212.22,3232.3232', 1 )
	r.zadd( 'hotfeet', 'p2,4512.22,9832.3232', 2 )
	r.zadd( 'hotfeet', 'p3,5212.22,5632.3232', 3 )
	r.zadd( 'hotfeet', 'p4,9812.22,2342.3232', 4 )

	t = r.zrevrange( "hotfeet", 0, -1 )
	for a in t:
		print a.split( ',' )
		
